package red.mlz.console.controller.material;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import red.mlz.console.annotations.VerifiedUser;
import red.mlz.console.domain.BaseContentValueVo;
import red.mlz.console.domain.BaseListVo;
import red.mlz.console.domain.material.MaterialInfoVo;
import red.mlz.console.domain.material.MaterialListVo;
import red.mlz.module.module.category.entity.Category;
import red.mlz.module.module.category.service.CategoryService;
import red.mlz.module.module.material.entity.Material;
import red.mlz.module.module.material.service.MaterialService;
import red.mlz.module.module.user.entity.User;
import red.mlz.module.utils.BaseUtils;
import red.mlz.module.utils.Response;
import red.mlz.module.utils.SpringUtils;

import java.math.BigInteger;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class MaterialController {

    @Autowired
    private MaterialService materialService;
    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/material/list")
    public Response materialList(@VerifiedUser User loginUser,
                                 @RequestParam(name = "page", required = false, defaultValue = "1") int page,
                                 @RequestParam(name = "keyword", required = false) String keyword) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        String pageSize = SpringUtils.getProperty("application.pagesize");
        String categoryIds = null;
        if (!BaseUtils.isEmpty(keyword)) {
            List<BigInteger> idsList = categoryService.getIdsByName(keyword);
            categoryIds = StringUtils.join(idsList, ",");
        }
        List<Material> materials = materialService.getMaterialsForConsole(page, Integer.parseInt(pageSize), keyword, categoryIds);
        String allCategoryIds = materials.stream()
                .filter(Objects::nonNull)  // 过滤掉 null
                .map(Material::getCategoryId)
                .distinct()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        List<Category> categoryList = categoryService.listByIds(allCategoryIds);
        Map<BigInteger, String> categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        int total = materialService.getMaterialsTotalForConsole(keyword, categoryIds);
        BaseListVo result = new BaseListVo();
        result.setTotal(total);
        result.setPageSize(Integer.valueOf(pageSize));
        List<MaterialListVo> list = new ArrayList<>();

        for (Material material : materials) {
            MaterialListVo entry = new MaterialListVo();
            entry.setId(material.getId());
            entry.setMaterialName(material.getName());
            entry.setCategoryName(categoryMap.get(material.getCategoryId()));
            entry.setProductName(material.getProductName());
            entry.setCreateTime(BaseUtils.timeStamp2Date(material.getCreateTime()));
            list.add(entry);
        }
        result.setList(list);
        return new Response(1001, result);
    }

    @RequestMapping("/material/info")
    public Response materialInfo(@VerifiedUser User loginUser,
                                 @RequestParam(name = "materialId") BigInteger materialId) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        Material material = materialService.getById(materialId);
        if (BaseUtils.isEmpty(materialId)) {
            return new Response(4004);
        }

        MaterialInfoVo entry = new MaterialInfoVo();
        entry.setMaterialId(material.getId());
        entry.setMaterialName(material.getName());
        entry.setProductName(material.getProductName());
        entry.setMaterialCount(material.getMaterialCount());
        if (!BaseUtils.isEmpty(material.getImageUrls())) {
            entry.setImageUrls(Arrays.asList(material.getImageUrls().split("\\$")));
        }
        entry.setCreateTime(BaseUtils.timeStamp2Date(material.getCreateTime()));
        entry.setUpdateTime(BaseUtils.timeStamp2Date(material.getUpdateTime()));
        try {
            List<BaseContentValueVo> contents = JSON.parseArray(material.getContent(), BaseContentValueVo.class);
            entry.setContent(contents);
        } catch (Exception cause) {
            // ignores
            return new Response(4004);
        }
        return new Response(1001, entry);
    }

    @RequestMapping("/material/create")
    public Response materialCreate(@VerifiedUser User loginUser,
                                   @RequestParam("name") String name,
                                   @RequestParam("categoryId") BigInteger categoryId,
                                   @RequestParam("productName") String productName,
                                   @RequestParam("materialCount") Integer materialCount,
                                   @RequestParam("imageUrls") String imageUrls,
                                   @RequestParam("content") String content,
                                   @RequestParam("tags") String tags) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        try {
            content = URLDecoder.decode(content, "utf8");
            materialService.editMaterial(null, name, categoryId, productName, materialCount, imageUrls, content, tags);
            return new Response(1001);
        } catch (Exception exception) {
            return new Response(4004);

        }
    }

    @RequestMapping("/material/modify")
    public Response materialModify(@VerifiedUser User loginUser,
                                   @RequestParam(name = "materialId") BigInteger materialId,
                                   @RequestParam("name") String name,
                                   @RequestParam("categoryId") BigInteger categoryId,
                                   @RequestParam("productName") String productName,
                                   @RequestParam("materialCount") Integer materialCount,
                                   @RequestParam("imageUrls") String imageUrls,
                                   @RequestParam("content") String content,
                                   @RequestParam("tags") String tags) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        Material old = materialService.getById(materialId);
        if (BaseUtils.isEmpty(old)) {
            return new Response(4004);
        }
        try {
            content = URLDecoder.decode(content, "utf8");
            materialService.editMaterial(materialId, name, categoryId, productName, materialCount, imageUrls, content, tags);
            return new Response(1001);
        } catch (Exception exception) {
            return new Response(4004);

        }
    }


    @RequestMapping("/material/delete")
    public Response materialDelete(@VerifiedUser User loginUser,
                                   @RequestParam(name = "materialId") BigInteger materialId) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        if (BaseUtils.isEmpty(materialId)) {
            return new Response(4004);
        }
        try {
            materialService.delete(materialId);
            return new Response(1001);
        } catch (Exception exception) {
            return new Response(4004);
        }
    }


}
